package controller;

import bean.Account;
import bean.AccountDAO;
import bean.SignInBean;
import framework.GetMapping;
import framework.ModelAndView;
import framework.PostMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;


public class AccountController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @GetMapping("/signinIndex")
    public ModelAndView signin() {
        return new ModelAndView("/signin.html");
    }

    @GetMapping("/answer")
    public ModelAndView answer(HttpSession session) {

        Account account = (Account) session.getAttribute("account");
        if (account == null) {
            return new ModelAndView("redirect:/signinIndex");
        }
        return new ModelAndView("/answer.html");
    }

    @PostMapping("/signin")
    public ModelAndView doSignin(SignInBean bean, HttpServletResponse response, HttpSession session) throws IOException {
        AccountDAO dao = new AccountDAO();
        Account account = dao.get(bean.accountName);

        if (account == null || !account.getPassword().equals(bean.password)) {
            response.setContentType("application/json");
            PrintWriter pw = response.getWriter();
            pw.write("{\"error\":\"Bad email or password\"}");
            pw.flush();
        } else {
            session.setAttribute("account", account);
            response.setContentType("application/json");
            PrintWriter pw = response.getWriter();
            pw.write("{\"result\":true}");
            pw.flush();

        }
        return null;
        // return new ModelAndView("/signin.html");

//        AccountDAO dao = new AccountDAO();
//        Account account = dao.get(accountName);
//        if (accountName == null || password == null || account == null || !password.equals(account.getPassword())) {
//            return new ModelAndView("signInFail.html");
//        } else {
//            session.setAttribute("account", account);
//            return new ModelAndView("redirect:/");
//        }
    }

    @GetMapping("/signout")
    public ModelAndView signout(HttpSession session) {
        session.removeAttribute("account");
        return new ModelAndView("redirect:/");
    }


    @GetMapping("/profile")
    public ModelAndView profile(HttpSession session) {
        Account account = (Account)session.getAttribute("account");
        if(null == account){
            return new ModelAndView("redirect:/signinIndex");
        }
        return new ModelAndView("/profile.html","account",account);
    }
}
